package de.hska.reka.websockets.client.annotationProcessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class WebSocketProcessor implements BeanPostProcessor,
		ApplicationContextAware {
	private ApplicationContext applicationContext;

	private BeanPostProcessor[] otherProcessors = new BeanPostProcessor[] {
			new WebSocketAnnotationProcessor()
	};

	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		for(BeanPostProcessor beanPostProcessor : this.otherProcessors) {
			((ApplicationContextAware)beanPostProcessor).setApplicationContext(this.applicationContext);
			bean = beanPostProcessor.postProcessAfterInitialization(bean, beanName);
			
		}
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		for(BeanPostProcessor beanPostProcessor : this.otherProcessors) {
			((ApplicationContextAware)beanPostProcessor).setApplicationContext(this.applicationContext);
			bean = beanPostProcessor.postProcessBeforeInitialization(bean, beanName);
		}
		return bean;
	}

	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		this.applicationContext = arg0;
		this.setApplicationContextOfSlaves();
	}

	private void setApplicationContextOfSlaves() {
		for (BeanPostProcessor beanPostProcessor : this.otherProcessors) {
			((ApplicationContextAware) beanPostProcessor)
					.setApplicationContext(this.applicationContext);
		}
	}
}
